import { Navigate, useRoutes, useLocation, useNavigate } from "react-router";
import Home from '@/pages/home'
import Login from '@/pages/login'
import Main from '@/pages/main'
import { useEffect, useState } from "react";
import { getListForUserAPI } from "./apis/auth";
const Routes = () => {

    const [authList, setAuthList] = useState<any[]>([]);
    const { pathname } = useLocation();
    const navigate = useNavigate();
    const token = sessionStorage.getItem('token');

    useEffect(()=>{

        // 是登录页直接放行，不进行任何操作
        if (pathname === '/login') return ;
        // 是否有token，有token，放行，没有token，跳转登录页
        if (!token){
            navigate('/login');
            return ;
        } 
        // 不是在登录页并且有token，判断是否已经获取过用户权限
        if (authList.length > 0) return;
        console.log('authList',authList);
        
        // 获取权限
        getListForUserAPI().then((res:any)=>{
            console.log(res,'2222222222');
            
            if (res.code === 10000) {
                setAuthList(res.data.list);
                console.log('111111');
                
            }
        })

    })
    let route:any = [
        {
            path:'/',
            element:<Navigate to='/login' />
        },
        {
            path:'/login',
            element:<Login />
        }
    ];

    if(token){
        route.push({
            path:'/',
            element:<Main />,
            children:[
                {
                    path:'home',
                    element:<Home />
                },
            ]
        })
    }
    const element = useRoutes(route)
    return element;
}

export default Routes;